﻿using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using llAma.Backend.Interface;

namespace socialdeveloperBackend
{
    public class Userdata : IUserData
    {
        private static Dictionary<int, string> mGpcDict = new Dictionary<int, string>();
        //Only the first lookup of each GPC will be sligthly slow.
        public static string GetGPCNameFromID(int id)
        {
            if (mGpcDict.ContainsKey(id)) return mGpcDict[id];

            lock (mGpcDict)
            {
                if (!mGpcDict.ContainsKey(id))
                {
                    using (MySqlConnection conn = SDBackend.CreateConnection())
                    {
                        using (MySqlDataReader dr = SDBackend.GetDataReader("SELECT * FROM tbl_gpcnames WHERE id = ?id;", conn, new MySqlParameter("?id", id)))
                        {
                            if (!dr.Read())
                            {
                                throw new InvalidOperationException("Tried to look up a GPC that didn't exist? Database problem?");
                            }
                            mGpcDict[id] = (string)dr["name"];
                        }
                    }
                }
                return mGpcDict[id];
            }

        }
        string mUsername;
        int mInternalID;
        int mGpcId = 0;
        string pk;
        public Userdata(MySqlDataReader dr)
        {
            //This is our base user data, We can fetch a copy of the connection at any time, cache what we have, and save it.
            mUsername = (string)dr["username"];
            mInternalID = (int)dr["id"];
            mGpcId = (int)dr["gpc"];
            pk = (string)dr["pk"];
        }

        string IUserData.getInfo(string key)
        {
            switch (key)
            {
                case "id":
                    return mInternalID.ToString();
                case "username":
                    return mUsername;
                case "symbol":
                    return SDBackend.CurrentInstance.GpcHandler.GetGPCSymbol(mGpcId);
                case "usericon":
                    return "0";
                case "gpc":
                    return GetMyGPC();
                case "gpc_id":
                    return mGpcId.ToString();
                case "token":
                    return pk;
                default:
                    return "Not Implemented.";
            }
        }

        private string GetMyGPC()
        {
            return GetGPCNameFromID(mGpcId);

        }

        void IUserData.setInfo(string key, string value)
        {
            throw new NotImplementedException();
        }

        bool IUserData.SecurityCheck(dAmn.Packet p)
        {
            return true;
        }
    }
}
